import csv, codecs
import numpy as np



def read_img_from_csv(csv_path):
    ''' read from Fluke ir img(csv format), and return numpy ndarray

    Returns:
        A numpy ndarray object which represent a gray scale image, each pixel value is the tempeture of the pixel
    '''
    with codecs.open(csv_path, 'r', 'utf-16-le') as csv_file:
        ir_reader = csv.reader(csv_file)
        line_index = 0
        ir_array = np.zeros([768, 1024])
        for row in ir_reader:
            if line_index >=5 and line_index <=772:
                for i in range(1024):
                    if '>' in row[i + 1]:
                        ir_array[line_index - 5][i] = row[i + 1].strip('>')
                    else:
                        ir_array[line_index - 5][i] = row[i + 1]
            line_index += 1
        csv_file.close()
        
        return ir_array

def save_as_pgm(filename, img):
    ''' save image to pgm format

    Args:
        filename: pgm file save path

        img: an 2D numpy ndarray which is a gray scale image 
    '''
    with open(filename, 'w+') as img_file:
        img_file.write('P2\n')
        img_shape = np.shape(img)
        img_file.write('%d %d\n' % img_shape[::-1])
        img_file.write('%d\n' % np.max(img))
        for row in img:
            for pixel in row:
                img_file.write('%d ' % int(pixel))
            img_file.write('\n')
    img_file.close()

if __name__ == '__main__':
    ir_array = read_img_from_csv(r"F:\工作\红外三维\处理后数据\csv\160622AA\AA062210.csv")
    print(ir_array)
    ir_temperatur_set = set()
    for row in ir_array:
        for temp in row:
            ir_temperatur_set.add(temp)
    print(len(ir_temperatur_set))

    save_as_pgm('aaa.pgm', ir_array)

